package com.studycard.ui;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.FindCallback;
import com.avos.avoscloud.SaveCallback;
import com.avoscloud.chat.base.App;
import com.avoscloud.chat.ui.activity.BaseActivity;
import com.example.studycard.R;
import com.studycard.bean.UriBean;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.app.Activity;
import android.app.LocalActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.BitmapFactory;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

public class BookCourseActivity extends BaseActivity {

	private Context context = null;
	private LocalActivityManager manager = null;
	private ViewPager pager = null;
	private TabHost tabHost = null;

	private int offset = 0;
	private int currIndex = 0;
	private int bmpW;
	private ImageView cursor;
	private TextView t1, t2;
	private RelativeLayout rel;
	private ImageButton bt_course;
	private String subjectId, userId;
	private TextView course_name, course_detail, course_teacher, course_place,
			teacher_description, schooltime;
	private ArrayList<HashMap<String, Object>> CourseDetail;// 存放网络加载下来并解析之后的数据
	private HashMap<String, Object> hashMap = new HashMap<String, Object>();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.bookcourse);
		context = BookCourseActivity.this;
		manager = new LocalActivityManager(this, true);
		manager.dispatchCreate(savedInstanceState);

		// 导入所需布局控件
		FindViewById();
		// 获取从SubjectManage页面传过来的值
		GetIntentData();
		// viewpage三大组成
		InitImageView();
		initTextView();
		initPagerViewer();

	}

	// 导入所需布局控件
	public void FindViewById() {
		initActionBar(App.ctx.getString(R.string.bookcourse));
		course_name = (TextView) findViewById(R.id.course_name);
		course_detail = (TextView) findViewById(R.id.course_in);
		bt_course = (ImageButton) findViewById(R.id.bt_course);
		course_teacher = (TextView) findViewById(R.id.course_teacher);
		teacher_description = (TextView) findViewById(R.id.teacher_description);
		course_place = (TextView) findViewById(R.id.course_place);
		schooltime = (TextView) findViewById(R.id.schooltime);

	}

	// 获取从SubjectManage页面传过来的值
	public void GetIntentData() {

		Intent intent = getIntent();
		Bundle bundle = intent.getExtras();
		Serializable s = bundle.getSerializable("list");
		CourseDetail = (ArrayList<HashMap<String, Object>>) s;
		int cPosition = bundle.getInt("position");
		String subjectDescription = bundle.getString("subjectDescription");
		String subjectName = bundle.getString("subjectName");
		hashMap = CourseDetail.get(cPosition);

		course_name.setText(subjectName);
		course_detail.setText("课程简介：" + subjectDescription);
		course_teacher.setText("教师名字：" + hashMap.get("teacher").toString());
		course_place.setText("上课地点：" + hashMap.get("place").toString());
		schooltime.setText("上课时间：" + hashMap.get("schooltime").toString());
		teacher_description.setText("教师描述:"
				+ hashMap.get("teacher_description").toString());
		bt_course.setOnClickListener(listener);

	}

	// 启动子线程
	private OnClickListener listener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub

			saveData();

		}
	};

	public void saveData() {
		subjectId = (String) hashMap.get("uuid");
		userId = AVUser.getCurrentUser().getObjectId();
		AVQuery<AVObject> query = new AVQuery<AVObject>("user_subject");
		query.whereEqualTo("subject_id", subjectId);
		query.whereEqualTo("user_id", userId);
		query.findInBackground(new FindCallback<AVObject>() {

			@Override
			public void done(List<AVObject> arg0, AVException arg1) {
				if (arg0.size() > 0) {
					Toast.makeText(BookCourseActivity.this, "已预订过该课程，不可重复预订",
							Toast.LENGTH_LONG).show();
				} else {
					AVObject userSubject = new AVObject("user_subject");

					userSubject.put("subject_id", subjectId);
					userSubject.put("user_id", userId);
					userSubject.saveInBackground(new SaveCallback() {

						@Override
						public void done(AVException arg0) {
							// TODO Auto-generated method stub
							if (arg0 == null) {
								Toast.makeText(BookCourseActivity.this,
										"预订成功，请到我的课表里面查看", Toast.LENGTH_LONG)
										.show();
							} else {

								Toast.makeText(BookCourseActivity.this, "预订失败",
										Toast.LENGTH_LONG).show();
							}
						}
					});

				}
			}
		});

	}

	private void initTextView() {
		t1 = (TextView) findViewById(R.id.tab1);
		t2 = (TextView) findViewById(R.id.tab2);
		t1.setOnClickListener(new MyOnClickListener(0));
		t2.setOnClickListener(new MyOnClickListener(1));

	}

	private void initPagerViewer() {
		pager = (ViewPager) findViewById(R.id.page);
		final ArrayList<View> list = new ArrayList<View>();
		Intent intent = new Intent(context, CourseArrangementActivity.class);
		list.add(getView("A", intent));
		Intent intent2 = new Intent(context, CourseCommentActivity.class);
		list.add(getView("B", intent2));

		pager.setAdapter(new MyPagerAdapter(list));
		pager.setCurrentItem(0);
		pager.setOnPageChangeListener(new MyOnPageChangeListener());
	}

	private void InitImageView() {
		cursor = (ImageView) findViewById(R.id.cursor);
		rel = (RelativeLayout) findViewById(R.id.layout);

		bmpW = BitmapFactory.decodeResource(getResources(), R.drawable.png)
				.getWidth();
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		int screenW = dm.widthPixels;
		offset = (screenW / 2 - bmpW) / 2;
		cursor.setBackgroundResource(R.drawable.png);
		rel.setPadding(offset, 0, 0, 0);

	}

	private View getView(String id, Intent intent) {
		return manager.startActivity(id, intent).getDecorView();
	}

	public class MyPagerAdapter extends PagerAdapter {
		List<View> list = new ArrayList<View>();

		public MyPagerAdapter(ArrayList<View> list) {
			this.list = list;
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			ViewPager pViewPager = ((ViewPager) container);
			pViewPager.removeView(list.get(position));
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}

		@Override
		public int getCount() {
			return list.size();
		}

		@Override
		public Object instantiateItem(View arg0, int arg1) {
			ViewPager pViewPager = ((ViewPager) arg0);
			pViewPager.addView(list.get(arg1));
			return list.get(arg1);
		}

		@Override
		public void restoreState(Parcelable arg0, ClassLoader arg1) {

		}

		@Override
		public Parcelable saveState() {
			return null;
		}

		@Override
		public void startUpdate(View arg0) {
		}
	}

	public class MyOnPageChangeListener implements OnPageChangeListener {

		int one = offset * 2 + bmpW;

		@Override
		public void onPageSelected(int arg0) {
			Animation animation = null;
			switch (arg0) {
			case 0:
				if (currIndex == 1) {
					animation = new TranslateAnimation(one, 0, 0, 0);
				}
				break;
			case 1:
				if (currIndex == 0) {
					animation = new TranslateAnimation(offset, one, 0, 0);
				}
				break;

			}
			currIndex = arg0;
			animation.setFillAfter(true);
			animation.setDuration(300);
			cursor.startAnimation(animation);
		}

		@Override
		public void onPageScrollStateChanged(int arg0) {

		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {

		}
	}

	public class MyOnClickListener implements View.OnClickListener {
		private int index = 0;

		public MyOnClickListener(int i) {
			index = i;
		}

		@Override
		public void onClick(View v) {
			pager.setCurrentItem(index);
		}
	};
}